package com.naiterui.ehp.ps.sms.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.beans.BeanUtil;
import com.naiterui.ehp.ps.sms.bean.Template;
import com.naiterui.ehp.ps.sms.cache.SmsRedisManager;
import com.naiterui.ehp.ps.sms.dao.ITemplateDao;
import com.naiterui.ehp.ps.sms.enums.PlatformType;
import com.naiterui.ehp.ps.sms.exception.ExceptionCodes;
import com.naiterui.ehp.ps.sms.exception.SmsBusinessException;
import com.naiterui.ehp.ps.sms.service.IPlatformService;
import com.naiterui.ehp.ps.sms.service.ISignatureService;
import com.naiterui.ehp.ps.sms.service.ITemplateService;
import com.naiterui.ehp.ps.sms.utils.FilterHtml;
import com.naiterui.ehp.ps.sms.utils.constants.SmsConstants;
import com.naiterui.ehp.ps.sms.vo.SignatureVO;
import com.naiterui.ehp.ps.sms.vo.TemplateVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 部门信息service层实现
 *
 * @author
 * @since 1.0.0
 */
@Slf4j
@Service
public class TemplateServiceImpl implements ITemplateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TemplateServiceImpl.class);

    @Autowired
    private ITemplateDao templateDao;

    @Autowired
    private ISignatureService signatureService;

    @Autowired
    private IPlatformService platformService;

    @Override
    public List<Template> getBySearch(Template template) {
        List<Template> templateList = templateDao.getBySearch(template);
        SignatureVO defaultSignature = signatureService.getDefaultSignature();
        // 获取默认签名，如果没有配置签名则设置为默认签名
        for (Template templateData : templateList) {
            templateData.setDescription(FilterHtml.xssProtect(templateData.getDescription()));
            if (templateData.getSignatureId() == null && defaultSignature != null) {
                templateData.setSignatureId(defaultSignature.getId());
            }
        }
        return templateList;
    }

    @Override
    public void addTemplate(TemplateVO templateVO, Integer[] platformIds) throws SmsBusinessException {

        if (platformIds.length > 1 && !StringUtils.isEmpty(templateVO.getMsgTemplateId())) {
            LOGGER.warn("填写三方短信平台模板ID时，不可选择多平台 msgTemplateId:{}", templateVO.getMsgTemplateId());
            throw new SmsBusinessException(ExceptionCodes.NOT_SELECT_MULTI_PLATFORM);
        }

        // 查询当前平台下模板ID是否已存在
        if (!StringUtils.isEmpty(templateVO.getTemplateId())) {
            for (Integer p : platformIds) {
                Template template = getTemplateByUnique(p, templateVO.getTemplateId());
                if (template != null) {
                    LOGGER.warn("当前平台模板已创建，如需编辑请点击修改 platformId:{}, templateId:{}", p, templateVO.getTemplateId());
                    throw new SmsBusinessException(ExceptionCodes.TEMPLATE_EXIST);
                }
            }
        } else {
            // 为当前多个平台生成系统统一的模板ID
            templateVO.setTemplateId(templateDao.getNextTemplateId());
        }

        for (Integer p : platformIds) {
            Template templateT = new Template();
            BeanUtils.copyProperties(templateVO, templateT);
            templateT.setCreatedAt(new Date());
            templateT.setPlatformId(p);
            templateT.setStatus(SmsConstants.EFFECTIVE_STAUTS);
            templateDao.saveOrUpdate(templateT);
            SmsRedisManager.addTemplate(templateT);
        }
    }

    @Override
    public Template getTemplateByID(Integer id) {
        Template template = templateDao.get(id);
        if (template != null && template.getSignatureId() == null) {// 签名id为空则置为默认签名
            SignatureVO defaultSignature = signatureService.getDefaultSignature();
            if (defaultSignature != null) {
                template.setSignatureId(defaultSignature.getId());
            }
        }
        return template;
    }

    @Override
    public Template getTemplateByUnique(Integer platformId, Integer templateId) {
        Template template = templateDao.getTemplateByUnique(platformId, templateId);
        return template;
    }

    @Override
    public TemplateVO getTemplateFromCache(Integer platformId, Integer templateId) {
        TemplateVO templateVO = SmsRedisManager.getTemplate(platformId, templateId);
        if (templateVO == null) {
            // 从数据库中回补
            Template template = getTemplateByUnique(platformId, templateId);
            templateVO = SmsRedisManager.addTemplate(template);
        }
        return templateVO;
    }

    @Override
    public void updateTemplate(Template oldTemplate, Template newTemplate) throws SmsBusinessException {
        if (oldTemplate == null) {
            throw new SmsBusinessException(ExceptionCodes.SMS_TEMPLATE_NOT_SET);
        }
        SmsRedisManager.deleteTemplate(oldTemplate.getPlatformId(), oldTemplate.getTemplateId());
        oldTemplate.setChangedAt(new Date());
        oldTemplate.setSignatureId(newTemplate.getSignatureId());
        oldTemplate.setMsgTemplateId(newTemplate.getMsgTemplateId());
        oldTemplate.setContent(newTemplate.getContent());
        oldTemplate.setDescription(newTemplate.getDescription());
        templateDao.saveOrUpdate(oldTemplate);
        SmsRedisManager.addTemplate(oldTemplate);
    }

    @Override
    public void updateTemplate(TemplateVO templateVO) throws BusinessException {
        if (templateVO == null || templateVO.getId() == null) {
            throw new SmsBusinessException(ExceptionCodes.SMS_TEMPLATE_NOT_SET);
        }
        Template template = getTemplateByID(templateVO.getId());
        if(template == null){
            throw new SmsBusinessException(ExceptionCodes.SMS_TEMPLATE_NOT_SET);
        }
        SmsRedisManager.deleteTemplate(template.getPlatformId(), template.getTemplateId());

        BeanUtil.copyPropertiesIgnoreNull(templateVO, template);
        template.setChangedAt(new Date());
        templateDao.saveOrUpdate(template);
        SmsRedisManager.addTemplate(template);
    }


    @Override
    public void deleteTemplateByID(Integer id) throws SmsBusinessException {
        Template template = getTemplateByID(id);
        if (template == null) {
            throw new SmsBusinessException(ExceptionCodes.SMS_TEMPLATE_NOT_SET);
        }
        templateDao.delete(template);
    }

    @Override
    public void updateTemplateStatus(Template template, int status) throws SmsBusinessException {
        if (template == null) {
            throw new SmsBusinessException(ExceptionCodes.SMS_TEMPLATE_NOT_SET);
        }
        if (template.getStatus() != status) {
            SmsRedisManager.deleteTemplate(template.getPlatformId(), template.getTemplateId());
            template.setStatus(status);
            template.setChangedAt(new Date());
            templateDao.saveOrUpdate(template);
            SmsRedisManager.addTemplate(template);
        }
    }

    @Override
    public void updateDefaultCoopenTemplateId(String templateId) {
      // 获取启用的短信平台
      Integer platformId = this.platformService.getCurrentPlatformFromCache();
      PlatformType platformType = PlatformType.typeFromValue(platformId);
      if (PlatformType.Cloopen.equals(platformType)) {
        log.info("当前启用短信平台【{}】, 执行默认短信模板初始化设置 templateId: {}", platformType.getName(), templateId);
        SignatureVO signatureVO = this.signatureService.getDefaultSignature();
        signatureVO.setCloopenTemplateId(templateId);
        try {
          this.signatureService.updateSignature(signatureVO);
        } catch (SmsBusinessException e) {
          log.warn("执行默认短信模板初始化设置 templateId: {}, 失败 ", templateId, e);
        }
      } else {
        log.info("当前启用短信平台【{}】", platformType.getName());
      }
    }

    @Override
    public Template getTemplateByTemplateId(String templateId) {
        Template template = templateDao.getTemplateByTemplateId(templateId);
        return template;
    }

    @Override
    public void updateTemplateForMsg(Template template) {
        if (template != null && template.getSignatureId() == null) {// 签名id为空则置为默认签名
            SignatureVO defaultSignature = signatureService.getDefaultSignature();
            if (defaultSignature != null) {
                template.setSignatureId(defaultSignature.getId());
            }
        }
        templateDao.saveOrUpdate(template);
    }
}
